﻿using System;
using System.IO;
using AppCommon;
using Controller;
using Model;

public partial class ACPanel_AddEditAdmin : System.Web.UI.Page
{
    public static int _id = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session[Constants.SESSION_ADMIN] == null)
            {
                // Ok
                Response.Redirect("~/ACPanel/");
            }
            BindDatatoDDL.BindPhanQuyen(ddlPhanquyen);
            var id = Request.QueryString["Id"];
            if (id != null)
            {
                id = id.Replace("'", "");
                _id = Convert.ToInt32(id);
                BindData(Convert.ToInt32(id));
            }
        }
    }

    public void BindData(int id)
    {
        try
        {
            var controller = new VYC17Controller();
            var list = controller.GetById(id);

            if (list.Count > 0)
            {
                tbUsername.Text = list[0].UserName;
                tbPassword.Text = list[0].Password; // 
                tbPasswordRetype.Text = list[0].Password; 
                ddlPhanquyen.SelectedValue = Convert.ToString(list[0].IdPhanQuyen);
                tbFullname.Text = list[0].HoTen;                
                cbTrangThai.Checked = Convert.ToBoolean(list[0].TrangThai);
            }
            else
            {
                // Du lieu khong ton tai
                litResult.Text = "<p class=\"alert alert-danger\">Lỗi! Dữ liệu không tồn tại..</p>";
            }
        }
        catch (Exception e)
        {
            // Du lieu khong ton tai
            litResult.Text = "<p class=\"alert alert-danger\">Lỗi! " + e.Message + "</p>";
            throw;
        }
    }

    protected void btnThemvao_OnClick(object sender, EventArgs e)
    {
        try
        {
            var controller = new VYC17Controller();
            var model = new ModelVYC17();

            model.UserName = tbUsername.Text;
            model.Password = tbPassword.Text;
            // Encrypt password
            model.PasswordHash = Common.Encrypt(model.Password + model.UserName);

            var passwordRetype = tbPasswordRetype.Text;
            // Neu password retype ma khac password thi yeu cau go lai va ngung xu ly
            if (!passwordRetype.Equals(tbPassword.Text))
            {
                litResult.Text = "<span class=\"alert alert-danger\">Lỗi! Password bạn nhập lại chưa đúng.</span>";
                return;
            }
            model.HoTen = tbFullname.Text;
            // Anh dai dien
            if (imgUploadAnhdaidien.HasFile)
            {
                var pathAnhbia = Server.MapPath(Constants.UPLOAD_KHACHHANG);
                if (!Directory.Exists(pathAnhbia))
                {
                    Directory.CreateDirectory(pathAnhbia);
                }
                // validate file image
                string[] validFileTypes = { "gif", "png", "jpg", "jpeg" };
                var extFile = Path.GetExtension(imgUploadAnhdaidien.PostedFile.FileName);
                var isValidate = false;

                if (extFile != null)
                {
                    foreach (var type in validFileTypes)
                    {
                        if (extFile.Equals("." + type))
                        {
                            isValidate = true;
                            break;
                        }
                    }
                }

                if (!isValidate)
                {
                    litResult.Text = "Invalid file with extension!";
                    model.AnhDaiDien = Constants.NO_IMAGE;
                }
                else
                {

                    litResult.Text = "Ok!";
                    // Luu file 
                    imgUploadAnhdaidien.SaveAs(pathAnhbia + tbUsername.Text + "_avatar_" + DateTime.Now.ToString("ddMMyyhhmmss") +
                                    extFile);
                    model.AnhDaiDien = tbUsername.Text + "_avatar_" + DateTime.Now.ToString("ddMMyyhhmmss") + extFile;
                }
            }
            else
            {
                model.AnhDaiDien = Constants.NO_IMAGE;
            }
            model.IdPhanQuyen = Convert.ToInt32(ddlPhanquyen.SelectedValue);
            model.TrangThai = Convert.ToInt32(cbTrangThai.Checked);

            var isSuccess = 0;
            if (_id != 0)
            {
                model.Id = _id;
                isSuccess = controller.EditData(model);
            }
            else
            {                
                isSuccess = controller.AddData(model);
            }

            if (isSuccess == 0)
            {
                // Chua thanh cong                
                litResult.Text = "<p class=\"alert alert-danger\">Lỗi! Thêm dữ liệu thất bại.</p>";
            }
            else
            {                
                litResult.Text = "<p class=\"alert alert-success\">Thêm dữ liệu thành công.</p>";
                ResetInput();
            }
        }
        catch (Exception)
        {
            litResult.Text = "<p class=\"alert alert-success\">Thêm dữ liệu thành công.</p>";
            ResetInput();
            throw;
        }
    }

    public void ResetInput()
    {
        tbUsername.Text = "";
        tbPassword.Text = "";
        tbPasswordRetype.Text = "";
        ddlPhanquyen.SelectedValue = "0";
        tbFullname.Text = "";
        cbTrangThai.Checked = false;
    }
}